
import { APP, AppCss, AppJs, AppParam, CallbackFn, LifeCycle, MicroProps } from "./types";
import { ConsoleLogger, SysMsgType } from './debug-log'
import _cloneDeep from "lodash/cloneDeep";
const console = new ConsoleLogger('微应用-主应用-App类')

export const activeApp =async (app: APP) => {
    const dic = window.__POWERED_BY_MICO__; 
    console.log('开始激活微应用');

    //如果在隔离就激活
    if (dic.partitionAppDic[app.name]) {
        dic.activeAppDic[app.name] = _cloneDeep(dic.partitionAppDic[app.name]);
        
        document.getElementById(app.domId.replace('#','')).appendChild(app.htmlElement); 
        if(dic.partitionAppDic[app.name].clientLife){
            dic.partitionAppDic[app.name].clientLife.mount({container:app.htmlElement});
        }
        delete dic.partitionAppDic[app.name];
        return false;
        // loadMicro({ domId: app.domId, name: app.name, baseUrl: app.baseUrl }) 
    }else{
        if(!document.getElementById(app.domId.replace('#','')).querySelector('#'+app.htmlElement.id)){
            document.getElementById(app.domId.replace('#','')).appendChild(app.htmlElement);
            await app.execApp(); 
            app.htmlElement=document.getElementById(app.htmlElement.id)
            dic.activeAppDic[app.name].htmlElement=document.getElementById(app.htmlElement.id); 
        }else{
            console.log('执行激活微应用，单当前应用未unmont');
            return false;
        }


        return true;
    }


} 

export const partitionApp =async (app: APP) => {
    const dic = window.__POWERED_BY_MICO__;
    //如果在隔离就激活
    if (dic.activeAppDic[app.name] && !dic.partitionAppDic[app.name]) {
        try {
            dic.partitionAppDic[app.name] = _cloneDeep(dic.activeAppDic[app.name]);
            delete dic.activeAppDic[app.name];
            //删除节点
            const parent = document.getElementById(app.htmlElement.id).parentElement;
            
            parent.removeChild(app.htmlElement)

            console.log('沙箱微应用成功', { partitionApp: dic.partitionAppDic[app.name] });
        } catch (e) {
            return
        } 
    } 
}

export class App implements APP {
    baseUrl: string;
    name: string;
    domId: string;
    appJs: AppJs[];
    appCss: AppCss[];
    htmlContent: string;
    htmlElement: HTMLElement;
    constructor(param: AppParam) {
        Object.keys(param).forEach((key) => {
            this[key] = param[key];
        })
    } 
    bootstrap=()=> {
        const dic = window.__POWERED_BY_MICO__;
        if (dic.activeAppDic[this.name].clientLife && dic.activeAppDic[this.name].clientLife.bootstrap) {
            dic.activeAppDic[this.name].clientLife.bootstrap({container:this.htmlElement})
            console.log('微应用-子应用bootstrap成功',{name:this.name})
        }
        console.log('bootstrap成功',{name:this.name})
    }
    mount=()=> {
        const dic = window.__POWERED_BY_MICO__;
        
        activeApp(this).then(res=>{
            if(res){
                if (dic.activeAppDic[this.name].clientLife && dic.activeAppDic[this.name].clientLife.mount) {
                    const props:MicroProps={container:this.htmlElement}
                    if(dic.globalState){
                        props.globalState!=dic.globalState
                    }
                    dic.activeAppDic[this.name].clientLife.mount(props);
                    console.log('微应用-子应用mount成功',{name:this.name})
                }
            }
      
            console.log('mount成功',{name:this.name})
        })
        console.log('激活微应用成功');

    }
    unmount=()=> { 
        const dic = window.__POWERED_BY_MICO__;
        if (dic.activeAppDic[this.name].clientLife && dic.activeAppDic[this.name].clientLife.unmount) {
            dic.activeAppDic[this.name].clientLife.unmount({container:this.htmlElement})
            console.log('微应用-子应用unmount成功',{name:this.name})
        }
        partitionApp(this);
    
        console.log('unmount成功',{name:this.name})
    } 
    distory=()=> { 
        const dic = window.__POWERED_BY_MICO__;
        this.htmlContent='';
        const name=this.name;
        this.htmlElement.parentElement.removeChild(this.htmlElement);  

        if (dic.activeAppDic[this.name]&&dic.activeAppDic[this.name].clientLife && dic.activeAppDic[this.name].clientLife.unmount) {
            dic.activeAppDic[this.name].clientLife.unmount({container:this.htmlElement}) 
        }
        if (dic.partitionAppDic[this.name]&&dic.partitionAppDic[this.name].clientLife && dic.partitionAppDic[this.name].clientLife.unmount) {
            dic.partitionAppDic[this.name].clientLife.unmount({container:this.htmlElement}) 
        } 
        this.htmlElement.innerHTML="";
        delete window.__POWERED_BY_MICO__.activeAppDic[this.name]
        delete window.__POWERED_BY_MICO__.partitionAppDic[this.name] 
        for(let ss in this){
            delete this[ss]
        } 
        console.log('distory成功',{name})
    } 
    clientLife: LifeCycle
    execApp = async () => {
        try {
            const proxy=window.__POWERED_BY_MICO__.clientAppDicProxy
            if(!proxy[this.name]){
                proxy[this.name]={}
            } 
            // window.document.getElementById(this.domId.replace('#','')).append(this.htmlElement)
            for(let i=0;i<this.appJs.length;i++){ 
                if(proxy[this.name][this.appJs[i].name]&&proxy[this.name][this.appJs[i].name].default){
                    proxy[this.name][this.appJs[i].name].default.default.mount({container:this.htmlElement}); 
                    return
                }
                 /* @vite-ignore */ 
                proxy[this.name][this.appJs[i].name]= await (async function(window,url){const res=await import(url);return res})(proxy,this.appJs[i].url) 
            }
            
            // this.appJs.forEach(async (appjs) => {
            //     console.log('开始加载微子应用', { name: this.name, appjsUrl: appjs.url })
            //     // ;(function(window, self){;${ scriptText }\n${ sourceUrl }}).bind(window.proxy)(window.proxy, window.proxy);
            //     // const func_callback=new Function(appjs.content);
            //     // const func_callback=new Function(appjs.content);
            //     // func_callback();
            //     // const text=import(`;(function(window, self){;${appjs.content}}).bind(window)(window, window);` )
            //     // const text=`import((function(window){${appjs.content}}).bind(window)(window.proxy); );`
            //     //import(
            //        // console.log('./'+appjs.name)
            //         // appjs.content.replace('./vendor.767872f1.js','http://127.0.0.1:8080/assets/vendor.767872f1.js')
            // // const res=await import(`import((function(window){${appjs.content}}).bind(window)(window.proxy); );`)
            // const res=await import(appjs.url)
            
            //     // eval(`;(function(window, self){;${ text}\n}).bind(window.proxy)(window.proxy, window.proxy);`);
            
            //   //  eval(`;(function(window, self){;${ import('data:text/javascript;charset=utf-8,' + encodeURIComponent(appjs.content) ) }\n}).bind(window.proxy)(window.proxy, window.proxy);`);
            // }) 
                
                //  this.mount();
         
            // await this.baseLife.unmount({ container: this.htmlElement });
            console.log('execApp-执行动态import结束', { name: this.name }); 
        } catch (e) {
            console.warn('加载出错', SysMsgType.js, { error: e });
            throw new Error('执行子应用失败')
        }

    }
}
